<template>
  <el-container>
    <el-header>
      <!--头部-->
      <Header></Header>
    </el-header>
    <br>
    <el-main>
      <!--搜索-->
      <Search></Search>
      <el-steps :active="2" finish-status="success" simple style="margin-top: 20px">
        <el-step title="查看购物车" ></el-step>
        <el-step title="确认订单信息" ></el-step>
        <el-step title="成功提交订单" ></el-step>
      </el-steps>
      <br>
      <h1>商品列表</h1>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="商品名称" prop="goodsName" style="width: 40%"></el-table-column>
        <el-table-column label="单价" prop="price" width="100px"></el-table-column>
        <el-table-column label="购买数量" prop="num" width="300px"></el-table-column>
        <el-table-column label="小计"  width="200px">
          <template slot-scope="scope">
            <span>{{scope.row.price*scope.row.num}}</span>
          </template>
        </el-table-column>

      </el-table>
      <div align="right" style="padding-top: 5px">
        <el-tag  type="primary">商品总价:{{totalPrice}}元</el-tag>
      </div>
      <h1>收货人信息</h1>

      <el-form ref="form" :inline="true" :model="dataForm" label-width="80px" >

        <el-form-item label="收货人">
          <template v-if="list.length>0">

            <el-select v-model="dataForm.name" placeholder="请选择收货人" @change="changeInfo">
              <template v-for="x in list">
                <el-option :label="x.name" :value="x.name"></el-option>
              </template>
            </el-select>

          </template>
          <template v-else>
              <el-input v-model="dataForm.name" placeholder="请选择收货人"></el-input>
          </template>

        </el-form-item>

        <el-form-item label="邮政编码">
          <el-input v-model="dataForm.postCode" ></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="dataForm.phone" ></el-input>
        </el-form-item>
        <el-form-item label="电子邮件">
          <el-input v-model="dataForm.email"></el-input>
        </el-form-item>

        <el-form-item label="收货地址">
          <el-input v-model="dataForm.address" style="width: 700px"></el-input>
        </el-form-item>
        <el-form-item >
          <el-button type="primary" @click="addReci">保存收货人信息</el-button>
        </el-form-item>
      </el-form>
      <h1>配送方式</h1>
        <el-radio-group v-model="postType" size="medium" @change="changePostPrice">
          <el-radio border label="申通"></el-radio>
          <el-radio border label="邮局平邮"></el-radio>
        </el-radio-group>
        <span v-show="stShow">申通配送费用：{{postPrice}}元</span>
       <span v-show="yjShow">邮局平邮配送费用：{{postPrice}}元</span>
      <h1>支付方式</h1>
      <el-radio-group v-model="payType" size="medium">
        <el-radio border label="微信"></el-radio>
        <el-radio border label="支付宝"></el-radio>
      </el-radio-group>
      <h1>订单附言</h1>
      <el-input type="textarea" placeholder="请输入订单附言" v-model="orderRemark"></el-input>

       <div align="right">
         <br>
         <el-tag  type="primary">应付金额:{{payPrice}}元</el-tag>
         <el-button type="primary" @click="sureOrder">确认订单</el-button>
       </div>



      <el-dialog
        title="支付宝支付"
        :visible.sync="isShow"
        width="30%">
        <div v-if="qrCodeUrl">
          <img :src="qrCodeUrl" width="300px" height="300px">
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="isShow = false">取 消</el-button>
            <el-button type="primary" @click="isShow = false">确 定</el-button>

      </span>
      </el-dialog>
    </el-main>
    <Footer></Footer>
  </el-container>
</template>

<script>
  import Header from "./myComponents/Header";
  import Search from "./myComponents/Search";
  import Footer from "./myComponents/Footer";
  import QRCode from 'qrcode';

  export default {
    name: "buyCarTwo",
    components:{
      Header,
      Search,
      Footer
    },
    data(){
      return{
        orderForm:{ //订单对象
          "orderMoney":0,
          "payMoney":0,
          "name":"",
          "address":"",
          "phone":"",
          "email":"",
          "postCode":"",
          "orderRemark":"",
          "orderDetailList":[],
          "salesList":[]
        },
        codeForm:{//支付宝二维码支付的参数
          out_trade_no:"",
          total_amount:0,
          subject:"",
          body:""
        },
        isShow:false,//控制弹窗是否显示
        qrCodeUrl:"",//二维码地址
        totalPrice:0,//总价
        tableData:[],
        list:[],//收货人列表
        //nameList:[],//收货人姓名列表
        dataForm: {
          name: '',//收货人
          postCode: '',//邮政编码
          phone: '',//电话
          email: '',//电子邮件
          address: ''//收货人地址
        },
        postType: "申通",//配送方式
        payType:"支付宝",//支付方式
        postPrice:15,//配送费用
        stShow:true,//默认显示申通费用信心
        yjShow:false,//默认不显示邮局费用信心
        orderRemark:"",//订单附言
        payPrice:0,//应付金额
        socket:null
      }
    },
    methods:{
      createWebSocket(){//创建webSocket
        this.socket = new WebSocket("ws://localhost:8080/alipaySocket");
        const self = this;
        //接收服务端发送过来消息
        this.socket.onmessage=function (msg) {
          console.log(msg.data);
          if(msg.data=="success"){
             self.$message("支付成功");
             self.isShow = false;
             //跳转到订单成功的页面
             self.$router.push({"name":"buyCarThree",query:{"num":self.codeForm.out_trade_no,"price":self.payPrice}})

          }
        }

      },
      queryReci(){//查询收货人
        const self = this;
        //清空
        //self.nameList =[];
        this.$http.get("/recipient/query",)
          .then(function (rs) {
             if(rs.data.code==200){
                self.list = rs.data.data;
                //self.nameList.push(rs.data.data.name);
             }else{
               //清空
               self.list =[];
             }
          })
      },

      addReci(){//保存收货人
          const self = this;
          this.$http.get("/recipient/add",{params:this.dataForm})
          .then(function (rs) {
               self.$message(rs.data.msg);
          })

      },
      countTotalPrice(){//计算总价
        if(this.tableData.length > 0){
          //初始化总价
          this.totalPrice =0;
          for(var i=0;i<this.tableData.length;i++){
            this.totalPrice += this.tableData[i].price*this.tableData[i].num;
          }

          //计算付款金额
          this.payPrice = this.totalPrice+this.postPrice;
        }
      },
      loadData(){//查询我的购物车
        const self = this;
        const http = this.$http.get("/car/queryCar");
        //成功调用
        http.then(function (rs) {
          if(rs.data.code==200){
            self.tableData = rs.data.data;
            //计算总价
            self.countTotalPrice();
            //更改购物车的数量
            console.log("=="+self.tableData.length);
            self.carNum =  self.tableData.length;

          }else{
            //清空
            self.tableData =[];
            self.$message("你的购物车没有数据");
          }
        })

      },
      changeInfo(){//收货人信息改变
          if(this.list.length>0){
              for(var i =0;i<this.list.length;i++){
                  if(this.list[i].name==this.dataForm.name){
                        this.dataForm.address = this.list[i].address;
                        this.dataForm.postCode = this.list[i].postCode;
                        this.dataForm.phone = this.list[i].phone;
                        this.dataForm.email = this.list[i].email;

                  }
              }
          }
      },
      changePostPrice(){//配送方式信息改变
            if(this.postType=="申通"){
                this.stShow = true;
                this.yjShow = false;
                this.postPrice = 15
            }else{
              this.stShow = false;
              this.yjShow = true;
              this.postPrice = 5;
            }
            //计算应付金额
            this.payPrice = this.totalPrice+this.postPrice;
      },
      sureOrder(){//确认订单
        //发送ajax
        const self = this;
        //定义订单对象参数
        this.orderForm.orderMoney = this.totalPrice;
        this.orderForm.payMoney = this.payPrice;
        this.orderForm.name = this.dataForm.name;
        this.orderForm.email = this.dataForm.email;
        this.orderForm.phone = this.dataForm.phone;
        this.orderForm.postCode = this.dataForm.postCode;
        this.orderForm.address = this.dataForm.address;
        this.orderForm.orderRemark =this.orderRemark;


        //定义订单明细 和 销售记录明细
        for(var i=0;i<this.tableData.length;i++){
          //创建订单明细对象
          const orderTail ={
            "sellerId":this.tableData[i].sallerId,
            "goodsId":this.tableData[i].goodsId,
            "goodsPrice":this.tableData[i].price,
            "goodsNum":this.tableData[i].num,
            "goodsMoney":this.tableData[i].price*this.tableData[i].num
          }
          //添加订单明细
          this.orderForm.orderDetailList.push(orderTail);
          //创建销售记录明细
           const sales =  {
               "goodsId":this.tableData[i].goodsId,
               "sellerId":this.tableData[i].sallerId,
               "quantity":this.tableData[i].num,
               "salesPrice":this.tableData[i].price,
               "amount":this.tableData[i].price*this.tableData[i].num
           }
           //添加销售明细
          this.orderForm.salesList.push(sales);
        }
        console.log(this.orderForm);
        //发发送ajax
        this.$http.post("/order-info/createOrder",this.orderForm)
        .then(function (rs) {
             if(rs.data.code==200){
                 //赋值订单编号
                self.codeForm.out_trade_no = rs.data.data;
                self.codeForm.total_amount = self.payPrice;
                self.codeForm.subject = self.countGoodsInfo();
                self.codeForm.body = self.orderRemark;
                //生成二维码
               self.myCode();
             }else{
               self.$message("订单异常");
             }
        })

      },
      countGoodsInfo(){//构建支付成功需要修改库存所需要的商品id和商品购买数量的参数格式
          var p = "";
          var id ="";
          var num ="";
          for(var i = 0;i<this.tableData.length;i++){
                id+= this.tableData[i].goodsId+",";
                num+=this.tableData[i].num+","
          }
          //获取用户名
          const userName = sessionStorage.getItem("userName");
          p = id+"&"+num+"&"+userName;
          console.log(p);
          return p;

      },
      myCode (){//生成二维码
        //显示付款二维码弹窗
        this.isShow = true;
        //发送ajax
        const self = this;
        this.$http.get("/order-info/creadeQrCode",{params:this.codeForm})
          .then(function (rs) {
            self.createCode(rs.data);
          })
      },
      //async ajax异步请求
      async createCode(url){
          const u = await QRCode.toDataURL(url);
          this.qrCodeUrl = u;
      }

    },
    mounted() {
      //查询购物车的订单数据
      this.loadData();
      //查询我的收货人列表
      this.queryReci();
      //创建支付的websocket
      this.createWebSocket();



    }

  }
</script>

<style scoped>

</style>
